package com.itheima.response;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
/*
    图片下载
 */
@WebServlet("/servletResponseDemo5")
public class ServletResponseDemo5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取下载文件名称
        String filename = req.getParameter("filename");
        System.out.println(filename);

        // 获取文件在服务器的输入流对象
        InputStream is = getServletContext().getResourceAsStream("/img/" + filename);

        // 设置响应头: 控制浏览器不要解析了, 以附件下载的方式处理服务器返回的数据
        resp.setHeader("content-Disposition","attachment;filename="+filename);

        // 获取字节输出流
        ServletOutputStream sos = resp.getOutputStream();

        // IO流拷贝
        IOUtils.copy(is,sos);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
